******************************************************************************** 
* import and merge and clean
******************************************************************************** 
use "build/output/lending_rates_wide.dta", clear

keep if coin == "USDT"
drop coin
merge 1:m date using "build/output/defillama.dta", nogen

tempfile tvl
preserve
keep if year(date) == 2022

tsset pool_id date
tsfill, full
drop if date <mdy(2,11,2022) // no defillama data before this date
replace tvlusd = 0 if missing(tvlusd)

collapse (mean) tvlusd, by(pool_id)
sort tvl
rename tvl tvl_2022_avg
egen tvl_2022_rank = rank(-tvl_2022_avg)
save `tvl'
restore

merge m:1 pool_id using `tvl', nogen
gen tvlusd_millions = tvlusd/1000000
sort pool_id date 

gen wdate = wofd(date)

******************************************************************************** 
* regression
******************************************************************************** 

eststo clear
eststo: reg apy margin_aprFTX if tvl_2022_rank<=1, r
estadd local tvl_weighted "No"
sum tvlusd_millions if tvl_2022_rank<=1
estadd scalar mean_size = `r(mean)', replace

eststo: reg apy margin_aprFTX if tvl_2022_rank<=3, r
estadd local tvl_weighted "No"
sum tvlusd_millions if tvl_2022_rank<=3
estadd scalar mean_size = `r(mean)', replace

eststo: reg apy margin_aprFTX if tvl_2022_rank<=5, r
estadd local tvl_weighted "No"
sum tvlusd_millions if tvl_2022_rank<=5
estadd scalar mean_size = `r(mean)', replace

eststo: reg apy margin_aprFTX if tvl_2022_rank<=10, r
estadd local tvl_weighted "No"
sum tvlusd_millions if tvl_2022_rank<=10
estadd scalar mean_size = `r(mean)', replace

eststo: reg apy margin_aprFTX [aw=tvl_2022_avg], r
estadd local tvl_weighted "Yes"
sum tvlusd_millions
estadd scalar mean_size = `r(mean)', replace

esttab, drop( _cons) star(* 0.10 ** 0.05 *** 0.01) r2 scalar(mean_size)
esttab using "analysis/output_tables/table_lending_rates_across_platforms.tex", replace booktabs label drop(_cons) ///
	prehead(\begin{tabular}{l S S S S S} \toprule) ///
	posthead(\midrule) postfoot(\bottomrule\end{tabular}) ///
	style(tex) substitute(\_ _) star  b(2) t(2) r2(2) ///
	nomtitles /// 
	varlabels(margin_aprFTX "\$\text{FTX Tether Lending Rate}_{t}\$") ///
	interaction(" $\times$ ") /// 
	star(* 0.10 ** 0.05 *** 0.01) ///
	mgroups("1 Largest" "3 Largest" "5 Largest" "10 Largest" "All" , pattern(1 1 1 1 1) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) ///
	stats(N r2 tvl_weighted mean_size, fmt(%9.0fc 2 0) layout("\multicolumn{1}{c}{@}" "\multicolumn{1}{c}{@}" "\multicolumn{1}{c}{@}" "\multicolumn{1}{c}{@}") labels(`"\$N\$"' `"\(R^{2}\)"' `"TVL Weighted"' `"Avg. TVL (\\$ millions)"'))
	
